<template>
  <div class="reset-password-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>重置您的密码</span>
        </div>
      </template>

      <div v-if="!message" class="form-content">
        <el-form
            :model="resetForm"
            :rules="rules"
            ref="resetFormRef"
            label-position="top"
            @submit.prevent="submitReset"
        >
          <el-form-item prop="newPassword">
            <el-input
                v-model="resetForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
                size="large"
            >
              <template #prefix>
                <el-icon><i class="fas fa-lock"></i></el-icon>
              </template>
            </el-input>
            <!-- 【集成】密码强度计组件 -->
            <PasswordStrengthMeter :password="resetForm.newPassword" />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
                v-model="resetForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                show-password
                size="large"
            >
              <template #prefix>
                <el-icon><i class="fas fa-check-circle"></i></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                @click="submitReset"
                :loading="isSubmitting"
                class="reset-button"
            >
              {{ isSubmitting ? '重置中...' : '确认重置' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div v-else class="result-message">
        <el-result
            :icon="isSuccess ? 'success' : 'error'"
            :title="isSuccess ? '操作成功' : '操作失败'"
            :sub-title="message"
        >
          <template #extra>
            <el-button type="primary" @click="router.push('/')">返回首页</el-button>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { userServie } from '@/services/user_service';
import { ElMessage } from 'element-plus';
// 【导入】密码强度检测工具和组件
import { checkPasswordStrength } from '@/utils/passwordStrength';
import PasswordStrengthMeter from "@/views/PasswordStrengthMeter.vue";

const route = useRoute();
const router = useRouter();

const token = ref('');
const message = ref('');
const isSubmitting = ref(false);
const isSuccess = ref(false);
const resetFormRef = ref(null);

const resetForm = reactive({
  newPassword: '',
  confirmPassword: ''
});

// 【修改】新密码的校验规则，加入强度检测
const validateNewPassword = (rule, value, callback) => {
  const strength = checkPasswordStrength(value);
  if (strength.score < 3) { // 要求强度至少为“中”
    callback(new Error('密码太弱，请组合使用大小写字母、数字或符号'));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== resetForm.newPassword) {
    callback(new Error('两次输入的密码不一致!'));
  } else {
    callback();
  }
};

// 【修改】更新表单校验规则
const rules = reactive({
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能少于8位', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
});

onMounted(() => {
  token.value = route.query.token;
  if (!token.value) {
    message.value = '无效的重置链接，请重新发起请求。';
    isSuccess.value = false;
  }
});

const submitReset = () => {
  if (!resetFormRef.value) return;
  resetFormRef.value.validate((valid) => {
    if (valid) {
      isSubmitting.value = true;
      userServie.resetPassword(token.value, resetForm.newPassword, (res) => {
        isSubmitting.value = false;
        if (res.code === 1000) {
          isSuccess.value = true;
          message.value = '密码重置成功！即将跳转到首页...';
          ElMessage.success('密码重置成功！');
          setTimeout(() => {
            router.push('/');
          }, 3000);
        } else {
          isSuccess.value = false;
          message.value = `错误: ${res.msg || '链接已失效或服务器错误'}`;
          ElMessage.error(message.value);
        }
      });
    } else {
      ElMessage.error('请检查您输入的内容');
      return false;
    }
  });
};
</script>

<style scoped>
.reset-password-container {
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 从顶部开始对齐 */
  min-height: calc(100vh - 80px); /* 减去header的高度 */
  padding-top: 5%; /* 顶部留出一些空间 */
  background-color: #f7f8fa; /* 更柔和的背景色 */
}

.box-card {
  width: 450px;
  border-radius: 12px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden; /* 确保子元素不会溢出圆角 */
}

.card-header {
  text-align: center;
  font-size: 1.5rem;
  font-weight: 500;
  color: #333;
}

.form-content {
  padding: 1rem 2rem 2rem 2rem;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input .el-icon {
  color: #c0c4cc;
}

.reset-button {
  width: 100%;
  height: 40px;
  font-size: 1rem;
  /* 匹配您的主题橙色 */
  background: linear-gradient(135deg, #ff9100 0%, #f99705 100%);
  border: none;
}

.reset-button:hover {
  opacity: 0.9;
  background: linear-gradient(135deg, #f99705 0%, #ff9100 100%);
}

.result-message {
  padding: 2rem;
}
</style>
